package com.jswdwsx.esign.commom

import com.jswdwsx.esign.cloud.exception.EsignException
import com.jswdwsx.esign.cloud.response.WebResult
import com.jswdwsx.esign.exception.EsignApiCallException
import com.jswdwsx.esign.util.Id
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@ControllerAdvice
class ExceptionHandler {

    private val logger = LoggerFactory.getLogger(ExceptionHandler::class.java)

    //普通业务的异常会被这个方法捕获
    @ExceptionHandler(EsignApiCallException::class)
    @ResponseBody
    fun handleEsignApiCallException(
        req: HttpServletRequest,
        rsp: HttpServletResponse,
        e: EsignApiCallException
    ): WebResult<Unit> {
        logger.warn("E签宝接口异常：[code - ${e.code}], [msg - ${e.message}]", e)
        return WebResult(e.code, e.message)
    }

    //普通业务的异常会被这个方法捕获
    @ExceptionHandler(EsignException::class)
    @ResponseBody
    fun handleEsignException(
        req: HttpServletRequest,
        rsp: HttpServletResponse,
        e: EsignException
    ): WebResult<Unit> {
        logger.warn("业务异常：[code - ${e.code}], [msg - ${e.message}]", e)
        return WebResult(e.code, e.message)
    }

    //处理其他异常
    @ExceptionHandler(Exception::class)
    fun handleOtherException(
        req: HttpServletRequest,
        rsp: HttpServletResponse,
        e: Exception
    ): WebResult<Unit> {
        var message: String = e.message ?: e.cause?.message ?: ""
        val httpStatus = HttpStatus.BAD_REQUEST

        logger.warn("业务异常：url:${req.requestURL}[msg - $message]", e)
        // 直接返回错误信息  不做多余转换
        return WebResult("${httpStatus.value()}001", message)
    }

    //500的异常会被这个方法捕获
    @ExceptionHandler(Throwable::class)
    fun handleError(
        req: HttpServletRequest,
        rsp: HttpServletResponse,
        e: Throwable
    ): WebResult<Unit> {
        val errNo = "${Id.ERROR.prefix}${UUID.randomUUID()}"
        logger.error("系统错误[{}]:", errNo, e)
        return WebResult("500001", e.message)
    }
}